package com.hadoop.mapreduce.FriendRelation;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * 以下是qq的好友列表数据，冒号前是一个用，冒号后是该用户的所有好友（数据中的好友关系是单向的）
 A:B,C,D,F,E,O
 B:A,C,E,K
 C:F,A,D,I
 D:A,E,F,L
 E:B,C,D,M,L
 F:A,B,C,D,E,O,M
 G:A,C,D,E,F
 H:A,C,D,E,O
 I:A,O
 J:B,O
 K:A,C,D
 L:D,E,F
 M:E,F,G
 O:A,H,I,J

 求出哪些人两两之间有共同好友，及他俩的共同好友都有谁？

 */

/**
 * 第一步 map  reduce  先找出“我”是谁的好友
 */
public class FriendRelation {
    static class FriendRelationMapper extends Mapper<IntWritable,Text,Text,Text>{
        Text keyText=new Text();
        Text valueText=new Text();
        @Override
        protected void map(IntWritable key, Text value, Context context) throws IOException, InterruptedException {
            String[] s = value.toString().split(":");
            keyText.set(s[0]);
            String[] friends = s[1].split(",");

            for (String friend :
                    friends) {
                valueText.set(friend);
                // 输出<好友，人>
                context.write(valueText,keyText);
            }
        }
    }

    static class FriendRelationReducer extends Reducer<Text,Text,Text,Text>{
        @Override
        protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            StringBuilder sb=new StringBuilder();
            for (Text text :
                    values) {
                String friend = text.toString();
                sb.append(friend+",");
            }

            context.write(key,new Text(sb.toString()));
        }
    }

    public static void main(String[] args) throws Exception {

        Configuration conf = new Configuration();
        conf.set("mapred.textoutputformat.separator", ":");
        Job job = Job.getInstance(conf);
        job.setJarByClass(FriendRelation.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        job.setMapperClass(FriendRelationMapper.class);
        job.setReducerClass(FriendRelationReducer.class);

        FileInputFormat.setInputPaths(job, new Path("D:/srcdata/friends"));
        FileOutputFormat.setOutputPath(job, new Path("D:/temp/out"));

        job.waitForCompletion(true);

    }
}
